package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.EsManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @version v1.0
 * @ProjectName: changgou_parent
 * @ClassName: EsManagerServiceImpl
 * @Description: TODO(一句话描述该类的功能)
 * @Author: Xu Fj
 * @Date: 2020/2/29 19:52
 */
@Service
public class EsManagerServiceImpl implements EsManagerService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private ESManagerMapper esManagerMapper;

    @Override
    public void createIndexAndMapping() {
        //创建索引库
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //映射索引库
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importAll() {
        //通过spuid查询出该商品的sku信息的集合
        List<Sku> listBySpuId = skuFeign.findListBySpuId("all");
        //判断
        if (listBySpuId == null || listBySpuId.size() <= 0){
            throw new RuntimeException("当前商品数据不存在");
        }
        //将sku集合转换成json串
        String skuJson = JSON.toJSONString(listBySpuId);
        //再讲sku的json串转换成es映射的实体类
        List<SkuInfo> skuInfos = JSON.parseArray(skuJson, SkuInfo.class);

        for (SkuInfo skuInfo : skuInfos) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void importDataToESBySpuId(String spuId) {
        //通过spuid查询出该商品的sku信息的集合
        List<Sku> listBySpuId = skuFeign.findListBySpuId(spuId);
        //判断
        if (listBySpuId == null || listBySpuId.size() <= 0){
            throw new RuntimeException("没有当前商品,无法导入"+spuId);
        }
        //将sku集合转换成json串
        String skuJson = JSON.toJSONString(listBySpuId);
        //再讲sku的json串转换成es映射的实体类
        List<SkuInfo> skuInfos = JSON.parseArray(skuJson, SkuInfo.class);

        for (SkuInfo skuInfo : skuInfos) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfos);


    }
}
